/*
 * logger.c ~ basic log support for error thwarting
 *
 * - Janis [04/10/2007]
 */

#include <allegro.h>
#include <stdarg.h> 
#include <stdio.h> 
#include "../include/logger.h"

PACKFILE *stream = NULL;
int can_log = 0;

int strt_log(const char * fn)
{
	stream = pack_fopen(fn, "w");
	can_log = (stream != NULL);
	return can_log;
}

void amazolog(const char *str, ...)
{
	if(!can_log) return;
	
	va_list ap;
	va_start(ap, str);
	
	// va_arg until out of args
	
	while(*str)
	{
		switch(*str)
		{
		case '%':
		{
			switch(*(++str))
			{
			case '%':
			{
				pack_putc('%', stream);
				printf("%%");
				break;
			}
			case 'd':
			{
				char * buf = malloc(8);
				char * org = buf;
				
				sprintf(buf, "%d", (int)va_arg(ap, int));
				while(*buf) {
					pack_putc(*buf, stream);
					printf("%c", *buf++);
				}
				free(org);
				break;
			}
			case 's':
			{
				char * substr = (char *)va_arg(ap, char*);
				while(*substr) {
					pack_putc(*substr, stream);
					printf("%c", *substr++);
				}
				break;
			}
			}
			break;
		}
		default:
			printf("%c", *str);
			pack_putc(*str, stream);
		}		
		++str;
	}
	
	va_end(ap);
}


void end_log()
{
	if(!can_log) return;
	pack_fclose(stream);
}
